from flask import Blueprint, jsonify
from app.models import db,Transaction

transaction_controller = Blueprint('transaction_controller', __name__)

@transaction_controller.get('/list')
def get_transaction():
    """
    GET /api/transaction/list
    获取交易记录
    """
    try:
        transaction = Transaction.query.all()
        result = [
            {
                'id': t.id,
                'products_id': t.products_id,
                'products_name': t.products_name,
                'userid': t.userid,
                'type': str(t.type).split('.')[-1],  # 移除前缀
                'trade_type': str(t.trade_type).split('.')[-1],  # 移除前缀
                'quantity': t.quantity,
                'trade_time': t.trade_time.strftime('%Y-%m-%d %H:%M:%S'),
                'trade_amount': t.trade_amount,
                'fee': t.fee
            }
            for t in transaction
        ]
        return jsonify({'code': 0, 'msg': '查询成功', 'data': result}), 200
    except Exception as e:
        return jsonify({'code': 1, 'msg': f'查询失败controller: {str(e)}'}), 500